package com.summer.safe.utils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.summer.safe.system.dao.DictDao;
import com.summer.safe.system.dao.DictTypeDao;
import com.summer.safe.system.entity.Dict;
import com.summer.safe.system.entity.DictType;

import java.util.List;
import java.util.Map;

import static com.summer.safe.utils.UserUtils.getCache;

/**
 * 字典工具类
 *
 *
 */
public class DictUtils {
    private static DictDao dictDao = SpringContextUtil.getBean(DictDao.class);
    private static DictTypeDao dictTypeDao = SpringContextUtil.getBean(DictTypeDao.class);


    public static String getDictLabel(String value, String type, String defaultValue) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)) {
            for (Dict dict : getDictList(type)) {
                if (type.equals(dict.getType()) && value.equals(dict.getValue())) {
                    return dict.getLabel();
                }
            }
        }
        return defaultValue;
    }

    /**
     * 字典数据
     * @param type
     * @return
     */
    public static List<Dict> getDictList(String type) {
        @SuppressWarnings("unchecked")
        Map<String, List<Dict>> dictMap = (Map<String, List<Dict>>) CacheUtils.get(Global.CACHE_DICT_MAP);
        if (dictMap == null) {
            dictMap = Maps.newHashMap();
            for (Dict dict : dictDao.findAllList(new Dict())) {
                List<Dict> dictList = dictMap.get(dict.getType());
                if (dictList != null) {
                    dictList.add(dict);
                } else {
                    dictMap.put(dict.getType(), Lists.newArrayList(dict));
                }
            }
            CacheUtils.put(Global.CACHE_DICT_MAP, dictMap);
        }
        List<Dict> dictList = dictMap.get(type);
        if (dictList == null) {
            dictList = Lists.newArrayList();
        }
        return dictList;
    }

    public static String getDictValue(String label, String type, String defaultLabel){
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)){
            for (Dict dict : getDictList(type)){
                if (type.equals(dict.getType()) && label.equals(dict.getLabel())){
                    return dict.getValue();
                }
            }
        }
        return defaultLabel;
    }
    /**
     * 获得字典类型
     */
    public static List<DictType> getDictTypeList(){
        List<DictType> dictTypeList = (List<DictType>)getCache(Global.CACHE_DICT_TYPE_MAP);
        if (dictTypeList == null){
            dictTypeList = dictTypeDao.findTypeList();
            UserUtils.putCache(Global.CACHE_DICT_TYPE_MAP, dictTypeList);
        }
        return dictTypeList;
    }
}
